<?php

namespace app\store\controller\ditui;

use app\store\controller\Controller;
use app\store\model\Store as StoreModel;
use think\Db;

class Dtuserok extends Controller
{
    public function index()
    {
        $paramArr = $this->request->param();
        $formInline = isset($paramArr['formInline']) ? $paramArr['formInline'] : "";
        $currentPage = isset($paramArr['currentPage']) ? $paramArr['currentPage'] : 1;
        $pageSize = isset($paramArr['pageSize']) ? $paramArr['pageSize'] : $this->SIZE30;
        $limit = " limit ".($currentPage-1)*$pageSize.", ".$pageSize;

        $order = " order by aa.dl_id desc";
        $where = " where aa.dl_shopid=".$this->ad_shopid." and aa.du_flowid=80 ";
        // 查找用户权限显示指定哪个班级的学员信息
        $showClassID = $this->store['user']['show_classid'];
        $showClassID>0 ? $where .= " and du_class=".$showClassID : "";

        $begTimeStr = "";
        $endTimeStr = "";
        if($formInline!=""){
            trim($formInline['startTime'])!="" ? $where .= " and aa.dl_addtime >= '".trim($formInline['startTime'])."'" : "";
            trim($formInline['endTime'])!="" ? $where .= " and aa.dl_addtime <= '".trim($formInline['endTime'])."'" : "";
            trim($formInline['phone'])!="" ? $where .= " and aa.du_mobile like '%".$formInline['phone']."%'" : "";
            trim($formInline['school'])!="" ? $where .= " and aa.du_school like '%".$formInline['school']."%'" : "";
            trim($formInline['name'])!="" ? $where .= " and aa.du_truename like '%".$formInline['name']."%'" : "";
            trim($formInline['remark'])!="" ? $where .= " and aa.du_zhmyremark like '%".$formInline['remark']."%'" : "";
            trim($formInline['xuehao'])!="" ? $where .= " and aa.dl_userid =".$formInline['xuehao'] : "";
            trim($formInline['sellerId'])!="" ? $where .= " and aa.dl_dituiuid =".$formInline['sellerId'] : "";
            trim($formInline['sex'])!="" ? $where .= " and aa.du_sex =".$formInline['sex'] : "";
            $flowint = trim($formInline['flowint']);    //此时用户的流程id，是表示用户的分班情况
            if($flowint!=""){
                if($flowint=='all'){
                    //$where .= " and aa.du_class >=0 ";
                }
                else{
                    $where .= " and aa.du_class = ".$flowint;
                }
            }
        }
        //ddd($where);
        //$sql = "select * from ".getTable('ditui_user').$where.$order.$limit;
        // 查询这个学员的消课情况
        $sqlHeader0 = "SELECT aa.*, bb.* ";
        $joinOne = "from ".getTable('ditui_user')." AS aa LEFT JOIN ( SELECT ux_dl_id, MAX(ux_ket_id) AS max_ux_ket_id FROM ".getTable('ditui_user_xiaoke')." GROUP BY ux_dl_id ) AS bb1 ON aa.dl_id = bb1.ux_dl_id";
        //$sqlHeader = getTable('ditui_user')." as aa left join ".getTable('ditui_user_xiaoke')." as bb on aa.dl_id=bb.ux_dl_id ";
        $joinTwo = " LEFT JOIN ".getTable('ditui_user_xiaoke')." AS bb ON aa.dl_id = bb.ux_dl_id AND bb.ux_ket_id = bb1.max_ux_ket_id";
        $sql = $sqlHeader0.$joinOne.$joinTwo.$where.$order.$limit;
        //ddd($sql);
        $list = Db::query($sql);

        //传递总数用于分页
        //$sqlNum = "select count(*) as allNum from ".getTable('ditui_user').$where;
        $sqlNum = "select count(*) as allNum ".$joinOne.$joinTwo.$where;
        $allNumArr = Db::query($sqlNum);

        //查询未分班的学员
        $backCallNum = "select count(*) as allNum from ".getTable('ditui_user')." as aa where aa.dl_shopid=".$this->ad_shopid." and aa.du_flowid=80 and aa.du_class = 0";
        $backCallNumArr = Db::query($backCallNum);

        //ddd($list);

        $keTabWidth = 1000;
        $kczdArr = $this->getKeZd();
        foreach($list as $key => $vvv){
            // 格式化沟通日志
            if($vvv['du_zhremarkstr']!=''){
                $list[$key]['zhmarkArr'] = json_decode($vvv['du_zhremarkstr'], true);
            }
            else{
                $list[$key]['zhmarkArr'] = [];
            }
            // 1. 计算当前的消课数量进度，获取课程名称
            // 2. 格式化课程对应的数组
            if($vvv['ux_xiaoke_txt']!=''){
                $list[$key]['kearr'] = json_decode($vvv['ux_xiaoke_txt'], true);
            }
            else{
                $arr1 = array();
                for($i=1; $i<31; $i++){
                    //k_type:0,无，10：正常消课，20：确课，30：请假，40：补课，50：自定义消课，可以消10节以上的课
                    $cellArr = array('k_dateStr'=>'', 'k_bukeDate'=>'', 'k_type'=>'0', 'k_use'=>'0', 'k_typestr'=>'', 'k_note'=>'', 'addtime'=>'');
                    $arr1[] = $cellArr;
                }
                $list[$key]['kearr'] = $arr1;
            }

            $perKcStr = $vvv['ux_ket_id']>0 ? $kczdArr['ke_'.$vvv['ux_ket_id']] : "";
            $list[$key]['ke_name'] =  $vvv['ux_ket_id']>0 ? explode("#",$perKcStr)[0] : '未设置';
            $list[$key]['xiaoke_jd'] =  $vvv['ux_xiaoke_jd']!=null ? $vvv['ux_xiaoke_jd'] : '0/30';

            $keTabWidth = count($list[$key]['kearr'])*60;
        }
        // 获取字段数组数据
        $bbb = $this->getZDarr();
        // 获取各个阶段的总数
        $allBigNumArr = $this->getPerAllNum($bbb['zhuanghuaArr'], $where);
        $allBigNumArr['allNum_all'] = $allNumArr[0]['allNum'];
        //$allBigNumArr['allNum_0'] = $backCallNumArr[0]['allNum'];   //未分班的总数，老版没加$where，getPerAllNum函数中重新计算
        $back['allBigNumArr'] = $allBigNumArr;
        //ddd($back);

        //ddd($list);
        if ($this->request->isAjax()) {
            $back['list'] = $list;
            $back['begTimeStr'] = $begTimeStr;
            $back['endTimeStr'] = $endTimeStr;
            $back['allNum'] = $allNumArr[0]['allNum'];
            $back['callBackNum'] = $backCallNumArr[0]['allNum'];
            return $this->renderSuccess('数据请求成功', '', $back);
        }
        //首次非ajax请求，直接控制器推送数据
        else{
            // 获取所有地推专员数据信息
            $sellerArr = Db::name('ditui_seller')->where(['ds_shopid'=>$this->ad_shopid])->select()->toArray();

            return $this->fetch('ditui/userok', ['data' =>['sellerArr'=>$sellerArr, 'keTabWidth'=>$keTabWidth, 'keArr'=>$bbb['keArr'], 'allBigNumArr'=>$allBigNumArr, 'schoolArr'=>$bbb['schoolArr'], 'flowArr'=>$bbb['flowArr'], 'zhuanghuaArr'=>$bbb['zhuanghuaArr'], 'list'=>$list, 'allNum'=>$allNumArr[0]['allNum'], 'callBackNum'=>$backCallNumArr[0]['allNum'] ]]);
        }
    }
    /**获取字典相关的数组*/
    private function getZDarr(){
        $zidianObj = Db::name('ditui_zidian')->where('dz_shopid', $this->ad_shopid)->find();
        if(!$zidianObj){
            $zidianCC = new Dtzidian();
            $zhuanghuaArr = $zidianCC->getArr(2);
            $schoolArr = $zidianCC->getArr(3);
            $keArr = $zidianCC->getArr(4);
        }
        else{
            $zhuanghuaArr = explode(',', $zidianObj['dz_fbtxtstr']);
            $schoolArr = explode(',', $zidianObj['dz_schoolstr']);
            $keArr = explode(',', $zidianObj['dz_kkccstr']);
        }
        //flowArr = ['all',0,1,2,3,4,5,6,7,8,100];  //组装转发标签卡
        $flowArr[] = 'all';
        $flowArr[] = 0;
        foreach ($zhuanghuaArr as $kkk => $vvv){
            $flowArr[] = ($kkk+1);
        }
        $flowArr[] = -1;
        $flowArr[] = -4;
        $flowArr[] = 100;

        $back['flowArr'] = $flowArr;
        $back['zhuanghuaArr'] = $zhuanghuaArr;
        $back['schoolArr'] = $schoolArr;
        $back['keArr'] = $keArr;
        return $back;
    }
    /**获取各个阶段的总数，此刻为获取各个班级的数据总数*/
    private function getPerAllNum($zhuanghuaArr, $where){
        $flowIdArr[] = 0;   //查询未分班的，包括了$where语句
        foreach ($zhuanghuaArr as $kkk => $vvv){
            $flowIdArr[] = $kkk+1;
        }
        $flowIdArr[] = -1;
        $flowIdArr[] = -4;
        $flowIdArr[] = 100;

        // 根据转化流程id查找对应的数据个数
        $back = array();
        foreach ($flowIdArr as $v2){
            $flowInt = $v2; //从零开始的转化，包括陌客0，成交80，回收站-1；
            $sqlNum = "select count(*) as allNum from ".getTable('ditui_user')." as aa ".$where. " and aa.du_class=".$flowInt;
            //echo $sqlNum.'<br>';
            $allNumArr = Db::query($sqlNum);
            $back['allNum_'.$flowInt] = $allNumArr[0]['allNum'];
        }
        //ddd($back);
        return $back;
    }

    /** 设置学员分班 */
    public function setClass()
    {
        $paramArr = $this->request->param();
        $opmStr = isset($paramArr['opmStr']) ? $paramArr['opmStr'] : 'move';
        $nowFlowInt = isset($paramArr['nowFlowInt']) ? $paramArr['nowFlowInt'] : 0;
        $backCallNextTime = isset($paramArr['backCallNextTime']) ? $paramArr['backCallNextTime'] : '';
        $opmDlidArr = isset($paramArr['opmDlidArr']) ? $paramArr['opmDlidArr'] : "";
        if($opmDlidArr!=""){
            if($opmStr=='backcall'){
                if(strtotime($backCallNextTime)<=time()){
                    return $this->renderError('回访时间必需大于当前时间');
                }
            }
            if(count($opmDlidArr)>0){
                $fruits_string = implode(', ', $opmDlidArr);
                $changeFiled = $opmStr=='move' ? " set du_class=".$nowFlowInt : " set du_nextcall='".$backCallNextTime."'";
                $update = "update ".getTable('ditui_user'). $changeFiled. " where dl_id in (".$fruits_string.")";
                //ddd($update);
                Db::query($update);
                $back['state'] = 'addOk';
                $back['msg'] = '分班成功';
                return $this->renderSuccess('分班成功', '', $back);
            }
        }
    }

    /**获取课程字典信息*/
    private function getKeZd(){
        $zidianObj = Db::name('ditui_zidian')->where('dz_shopid', $this->ad_shopid)->find();
        if(!$zidianObj){
            $zidianCC = new Dtzidian();
            $keArr = $zidianCC->getArr(4);
        }
        else{
            $keArr = explode(',', $zidianObj['dz_kkccstr']);
        }

        $backArr = array();
        foreach ($keArr as $kk => $vv){
            $backArr['ke_'.($kk+1)] = $vv;
        }

        return $backArr;
    }

    /** 批量上传学员数据 */
    public function piliAddstudent(){
        $file = $this->request->file('file');
        if($file){
            // 移动文件到指定目录
            $info = $file->move('./uploads/csv');

            if ($info) {
                // 读取 CSV 文件内容
                $filePath = './uploads/csv/' . $info->getSaveName();
                // 检查文件是否存在
                if (!file_exists($filePath)) {
                    return $this->renderError('未找到保存的文件');
                }
                $csvData = $this->readCsvFile($filePath);
                //ddd($csvData);
                //设置批量上传参数
                $inArr = $this->piliangIndb($csvData);
                $back['code'] = 1;
                $back['msg'] = '修改成功';
                $back['csvdata'] = $csvData;
                $back['inArr'] = $inArr;
                echo json_encode($back, true);
            }
            else{
                $back['code'] = 0;
                $back['msg'] = '文件未上传完成';
                echo json_encode($back, true);
            }
        }
        else {
            $back['code'] = 0;
            $back['msg'] = '未接收到文件';
            echo json_encode($back, true);
        }
    }
    private function readCsvFile($filePath){
        $rows = array();
        // 打开文件
        if (($handle = fopen($filePath, 'r')) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // 将每行数据添加到数组中
                foreach($data as $key => $val){
                    $data[$key] = iconv('gbk','utf-8', $val.'');
                }
                $rows[] = $data;
            }
            // 关闭文件指针
            fclose($handle);
        }
        return $rows;
    }
    private function piliangIndb($csvData){
        $inArr = array();
        $updateArr = array();
        foreach($csvData as $key => $val){
            $mobile = trim($val[3]);
            if($mobile!="" && $key>0){
                //检查该手机号是否已经入库
                $isInObj = Db::name('ditui_user')->field('dl_id,du_flowid')->where('du_mobile', $mobile)->find();
                if(!$isInObj) {
                    $perArr['dl_shopid'] = $this->ad_shopid;
                    $perArr['dl_shopname'] = $this->ad_shopname;
                    $perArr['dl_channel'] = '批量导入';
                    $perArr['du_flowid'] = 80;
                    $perArr['du_mobile'] = $mobile;
                    $perArr['du_truename'] = trim($val[0]) != '' ? trim($val[0]) : '';
                    $perArr['du_school'] = trim($val[1]) != '' ? trim($val[1]) : '';
                    $perArr['du_grade'] = trim($val[2]) != '' ? trim($val[2]) : '';
                    $perArr['wxapp_id'] = $this->wxapp_id;
                    $perArr['dl_dituiname'] = '导入 (' . $this->admin_realname . ')';
                    $perArr['dl_addtime'] = date('Y-m-d H:i:s', time());
                    $inArr[] = $perArr;
                }
                else{
                    if($isInObj['du_flowid']!=80){
                        $updateArr[] = $isInObj['dl_id'];
                    }
                }
            }
        }
        //ddd($inArr);
        if(count($updateArr)>0){
            $fruits_string = implode(', ', $updateArr);
            $update = "update ".getTable('ditui_user'). " set du_flowid=80 where dl_id in (".$fruits_string.")";
            Db::query($update);
        }
        $result = Db::name('ditui_user')->insertAll($inArr);
        return $inArr;
    }
}
